package com.notion.algorithms.datastructures.graph;

import java.util.HashMap;
import java.util.Map;

import com.notion.algorithms.datastructures.graph.Vertex;

/**
 * Cluster utility class to perform various operations
 * @author samurai
 *
 */
public class Clusters {
	//To fetch cluster to which a vertex belongs
	private static Map<Vertex,Cluster> vertexClusterMap = new HashMap<Vertex, Cluster>();
	//count number of clusters as they disappear
	private static int currentClusterCount;
	public static int getCurrentClusterCount(){
		return currentClusterCount;
	}
	public static void setTotalNoOfVertices(int noOfVertices){
		currentClusterCount = noOfVertices;
	}
	/**
	 * use it to find what is the max spacing finally
	 */
	public static boolean areVerticesInSameCluster(Vertex v1, Vertex v2){		
		return vertexClusterMap.get(v1)==vertexClusterMap.get(v2);
	}

	public static void mergeClustersOfVertices(Vertex v1, Vertex v2){
		Cluster c1 = vertexClusterMap.get(v1);
		Cluster c2 = vertexClusterMap.get(v2);
		if(c1!=c2){			
			//merge the smaller of 2 clusters
			if(c1.getClusterVertexCount()<c2.getClusterVertexCount()){
				mergeCluster2IntoCluster1(c2, c1);
			}
			else{
				mergeCluster2IntoCluster1(c1, c2);
			}
			//1 cluster disappeared
			currentClusterCount--;
		}
	}
	
	public static void addVertexCluster(Vertex v, Cluster c){
		vertexClusterMap.put(v, c);
	}
	private static void mergeCluster2IntoCluster1(Cluster cluster1, Cluster cluster2){
		for(Vertex v:cluster2.getClusterVertices()){
			vertexClusterMap.put(v, cluster1);
			cluster1.addVertexToCluster(v);
		}
	}
}
